/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package runapplication;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 *
 * @author mani
 */
public class XmlClass {

    private String xmlfilename;
    private Document rootdoc;

    XmlClass(String udir, String file) throws DocumentException {
       
        xmlfilename = udir +  File.separatorChar +"xml" + File.separatorChar+ file;
        SAXReader sr2 = new SAXReader();
        rootdoc = sr2.read(xmlfilename);
    }

    void Save() throws IOException {
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter write = new XMLWriter(new FileWriter(xmlfilename), format);
        write.write(rootdoc);
        write.close();
    }

    Element getRootElement() {
        return rootdoc.getRootElement();
    }

    void SaveToUpdate(String yahoo, double todayclose, double lastclose) {
    }

    void SaveTrue(String yahoo, double todayclose, double lastclose) {
        Element rootElement = getRootElement();
        Iterator elementIterator = rootElement.elementIterator();
        while (elementIterator.hasNext()) {
            Element next = (Element) elementIterator.next();
            String value = next.attribute("yahoo").getValue();
            if (value.compareToIgnoreCase(yahoo) == 0) {
                S2D today = new S2D("2000-01-01");
                next.addAttribute("updateDate", today.getTodayChinese());
                if (next.attribute("true").getValue().compareTo("true") == 0) {
                    next.addAttribute("true", "");
                } else {
                 
                    if (next.attribute("true").getValue().isEmpty()) {
                        next.addAttribute("true", String.format("%.5f", (todayclose - lastclose) / lastclose));
                    } else {
                        next.addAttribute("true", next.attribute("true").getValue() + "," + String.format("%.5f", (todayclose - lastclose) / lastclose));
                    }
                }

                break;
            }
        }
    }

    void SaveFalse(Element next, double tomorrow) {
        Attribute attribute = next.attribute("false");
        if (attribute.getValue().isEmpty()) {
            String value = attribute.getValue();
            next.addAttribute("false", String.format("%.5f", tomorrow));
        } else {
            String value = attribute.getValue();
            next.addAttribute("false", value + "," + String.format("%.5f", tomorrow));
        }
    }
}
